import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import './index.css';
export default class List extends Component {
  state = {
    users: [], // 存放所有用户
    isFirst: true, // 是否第一次进入
    isLoading: false, // 是否正在加载
    err: '', // 存储请求错误信息
  };
  componentDidMount() {
    this.token = PubSub.subscribe('search_user', (_, stateObj) => {
      this.setState(stateObj);
    });
  }
  componentWillUnmount() {
    PubSub.unsubscribe(this.token);
  }
  render() {
    const { users, isFirst, isLoading, err } = this.state;
    return (
      <div className='row'>
        {isFirst ? (
          <h3 style={{ marginLeft: '20px', color: '#666' }}>
            请输入关键字，搜索用户
          </h3>
        ) : isLoading ? (
          <h3 style={{ marginLeft: '20px' }}>加载中...</h3>
        ) : err ? (
          <h3 style={{ marginLeft: '20px', color: 'red' }}>{err}</h3>
        ) : (
          users.map((userObj) => {
            return (
              <div key={userObj.id} className='card'>
                <a href={userObj.html_url} target='_blank'></a>
                <img
                  src={userObj.avatar_url}
                  style={{ width: '100px' }}
                  alt='head_portrait'
                />
                <p className='card-text'>{userObj.login}</p>
              </div>
            );
          })
        )}
      </div>
    );
  }
}
